/*
 * Created on 14/04/2004
 * 
 * To change the template for this generated file go to Window - Preferences -
 * Java - Code Generation - Code and Comments
 */
package gminet.infra.db;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author C1078305
 * 
 * To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Generation - Code and Comments
 */
public class DBConnection {

    private Connection realConnection;

    private long startTime;

    private long timeOut;

    /**
         * 
         */
    public DBConnection(Connection realConnection, long timeOut) throws SQLException {

	super();
	this.realConnection = realConnection;
	this.realConnection.setAutoCommit(false);
	this.startTime = System.currentTimeMillis();
	this.timeOut = timeOut;
    }

    protected boolean isValid() throws SQLException {

	boolean connectionOk = true;
	try {
	    connectionOk = (this.realConnection != null) && (!this.realConnection.isClosed());
	} catch (SQLException sqle) {
	    try {
		realConnection.close();
	    } catch (SQLException sqle2) {
		//
	    } finally {
		realConnection = null;
	    }
	    throw new SQLException("Connection is broke.");
	}
	return connectionOk;
    }

    protected boolean isTerminated() throws SQLException {

	boolean connectionOk = isValid();
	if (this.timeOut > 0) {
	    long remaining = timeOut - (System.currentTimeMillis() - this.startTime);
	    connectionOk &= remaining > 0;
	}
	return !connectionOk;
    }

    protected Connection getConnection() throws SQLException {

	if (isTerminated()) {
	    throw new SQLException("Connection time-out.");
	}
	return getRealConnection();
    }

    protected Connection getRealConnection() throws SQLException {

	Connection conn = null;
	if (isValid()) {
	    conn = this.realConnection;
	}
	return conn;
    }

    protected boolean isClosed() throws SQLException {

	return getRealConnection().isClosed();
    }

    protected Statement createStatement() throws SQLException {

	return getRealConnection().createStatement();
    }

    protected void close() throws SQLException {

	getRealConnection().close();
    }

}
